#include "app_message.h"
//将字符数组转换为json字符串
//return:json字符串
//chars:字符数组
//len:字符数组数据三长度

char *app_message_charsToJson(char *chars, int len)
{
//从chars中读取conn_type,id_len,msg_len,id,msg
    int conn_type = chars[0];
    int id_len = chars[1];
    int msg_len = chars[2];
    char id[id_len];
    char msg[msg_len];
    memcpy(id, chars + 3, id_len);
    memcpy(msg, chars + 3 + id_len, msg_len);
    //将id和msg转换为十六进制字符串
    char *id_hex = app_message_charsToHex(id, id_len);
    char *msg_hex = app_message_charsToHex(msg, msg_len);
    //生成包含conn_type,id_hex,msg_hex的json字符串
    cJSON *root_obj = cJSON_CreateObject();
    cJSON_AddNumberToObject(root_obj, "conn_type", conn_type);
    cJSON_AddStringToObject(root_obj, "id", id_hex);
    cJSON_AddStringToObject(root_obj, "msg", msg_hex);
    char *json = cJSON_PrintUnformatted(root_obj);
    //释放内存
    cJSON_Delete(root_obj);
    free(id_hex);
    free(msg_hex);
    return json;
    
}
//将json字符串转换为字符数组
//return:字符数组长度,-1表示失败
//json:json字符串
//chars_buff:字符数组
//buff_len:字符数组长度
/**
 字符数组:  1 2 4 XXabcd
 json字符串: {"conn_type": 1, "id": "5858", "msg": "61626364"}
 */
int app_message_jsonToChars(char *json,char *chars_buff, int buff_len)
{
    //解析json字符串得到conn_type,id_hex,msg_hex
    cJSON *root_obj = cJSON_Parse(json);
   int conn_type = cJSON_GetObjectItem(root_obj, "conn_type")->valueint;
   char *id_hexstr = cJSON_GetObjectItem(root_obj, "id")->valuestring;
   char *msg_hexstr = cJSON_GetObjectItem(root_obj, "msg")->valuestring;
   //将id_hexstr和msg_hexstr转换为字符数组id,msg
   int id_len = -1;
   int msg_len = -1;
   char *id_chars = app_message_hexToChars(id_hexstr, &id_len);
   char *msg_chars = app_message_hexToChars(msg_hexstr, &msg_len);
   //字符数组消息的长度
   int chars_len =3+id_len+msg_len;
   //判断字符数组长度是否超过buff_len
   if(chars_len>buff_len)
   {
    log_error("字符数组长度超过buff_len");
       return -1;
   }
   //将conn_type,id_len,msg_len,id,msg写入字符数组
   chars_buff[0] = conn_type;
   chars_buff[1] = id_len;
   chars_buff[2] = msg_len;
   memcpy(chars_buff+3, id_chars, id_len);
   memcpy(chars_buff+3+id_len, msg_chars, msg_len);
   //释放内存
   free(id_chars);
   free(msg_chars);
   cJSON_Delete(root_obj);
   return chars_len;


}